package IOStream_etc.FileStream_etc;

import org.junit.Test;

import java.io.*;

/**
 * @author Jimmy Zhan WORKSTATION
 * @date 2023/3/28 21:03
 * 说明：使用字符流(reader, writer)难以复制文本以外的文件，但是使用字节流(FileInputStream, FileOutputStream)可以实现
 */

public class FileStreamTest {
    @Test
    public void test1(){
        // 1. 创建相关File类的对象
        File srcFile = new File("playboy.jpg");
        File desFile = new File("playboy_copy.jpg");
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            // 2. 创建相关字节流
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(desFile, true);

            // 3. 数据的读入和写出
            byte[] buffer = new byte[1024];
            int len; // 记录每次读入到buffer中字节的个数
            while ((len = fis.read(buffer)) != -1){
                fos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 4. 关闭资源
            try {
                if (fos != null) fos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                if (fis != null) fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
